package com.ykt.model;

import java.util.List;

import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.ehcache.CacheKit;
import com.ykt.interceptor.Seach;



public class User extends SeachModel<User>{
	private static final long serialVersionUID = 1L;
	public final static User dao = new User();
	
	public List<String>getRolesName(String loginName){
		String sql="select r.name from user u "
				+ "inner join user_role ur on u.id = ur.user_id "
				+ "inner join role r on r.id=ur.roleid "
				+ "where u.name=?";
		return getAttr(sql, "name", loginName);
	}
	public User checkUser(String name,String pwd){
		String sql="select * from user where name =? and password=? ";
		return findFirst(sql, name,pwd);
	}
	
	public Role getRole(){
		return Role.dao.findById(this.get("role_id"));
	}
	public Shop getShop(){
		return Shop.dao.findById(get("id"));
	}
	@Override
	public Page<User> paginate(int pageNumber, int rows, Seach seach) {
		return super.paginateHasShop(pageNumber, rows, seach);
	}
	/**
	 * 获取主要的菜单分组
	 * @return
	 */
	public List<Menu> getMenu(){
		String sql="select DISTINCT ppm.* "
				+ "from role r "
				+ "inner join role_menu rm "
				+ "on r.id = rm.role_id "
				+ "inner join menu m "
				+ "on rm.menu_id = m.id "
				+ "inner join user_role ur "
				+ "on  ur.role_id = r.id "
				+ "inner join user u "
				+ "on ur.user_id = u.id "
				+ "inner join menu pm "
				+ "on m.pid = pm.id "
				+ "inner join menu ppm "
				+ "on pm.pid = ppm.id "
				+ "where ur.user_id = ? "
				+ "order by ppm.seq";
		return Menu.dao.findByCache("authority","menu_"+get("id"),sql,get("id"));
	}
	/**
	 * 根据PID查询所以子menu
	 * @param pid
	 * @return
	 */
	public List<Menu> getMenuSub(Integer pid){
		String sql="select DISTINCT pm.* "
				+ "from role r "
				+ "inner join role_menu rm "
				+ "on r.id = rm.role_id "
				+ "inner join menu m "
				+ "on rm.menu_id = m.id "
				+ "inner join user_role ur "
				+ "on  ur.role_id = r.id "
				+ "inner join user u "
				+ "on ur.user_id = u.id "
				+ "inner join menu pm "
				+ "on m.pid = pm.id "
				+ "inner join menu ppm "
				+ "on pm.pid = ppm.id "
				+ "where ur.user_id = ? and ppm.id=? "
				+ "order by pm.seq";
		return Menu.dao.findByCache("authority","menusub_"+get("id")+"_"+pid,sql,get("id"),pid);
	}
	/**
	 * 得到所有操作类型的menu
	 * 缓存 authority menuCommon_get("id")
	 * @param pid
	 * @return
	 */
	public List<Menu> getMenuCommon(){
		String sql="select DISTINCT m.*  "
				+ "from menu m "
				+ "inner join role_menu rm "
				+ "on rm.menu_id = m.id "
				+ "inner join role r "
				+ "on rm.role_id = r.id "
				+ "inner join user_role ur "
				+ "on ur.role_id=r.id "
				+ "where  ur.user_id=? and m.type=1";
		
		return Menu.dao.findByCache("authority","menuCommon_"+get("id"),sql,get("id"));
	}
}
